<?php

namespace Beerus\Modules\Designer\Actions;

use Doraemon\model\DesignerAuth;
use Encore\Admin\Actions\RowAction;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;

class OperateTag extends RowAction
{
    public $name = '设置能力标签';

    const OPTIONAL_TAG_THIRD_SS = 1; //第三方监理服务
    const OPTIONAL_TAG = [
        self::OPTIONAL_TAG_THIRD_SS => "第三方监理服务",
    ];

    public function handle($id, Request $request)
    {
        $ability_tag = array_filter($request->post('ability_tag_op'));
        $ability_tag = array_map(function ($v){return self::OPTIONAL_TAG[$v];}, $ability_tag);
        $res = DesignerAuth::update([
            'ability_tag_op' => $ability_tag ? implode(',', $ability_tag) : '',
            'update_time' => date("Y-m-d H:i:s")
        ], [
            'id' => $id,
        ]);

        if ($res) {
            return $this->response()->success('操作成功')->refresh();
        }else{
            return $this->response()->error('操作失败,请稍后重试');
        }
    }

    public function retrieveModel(Request $request)
    {
        if (!$key = $request->get('_key')) {
            return false;
        }

        return $key;
    }

    public function form($request)
    {
        $uid = $request->uid;
        $info = DesignerAuth::getByUId($uid);
        $checked = explode(',', $info["ability_tag_op"]);
        $ability_tag_checked = [];
        foreach ($checked as $v) {
            if (in_array($v, self::OPTIONAL_TAG)) {
                $key = array_search($v, self::OPTIONAL_TAG);
                $ability_tag_checked[$key] = $v;
            }
        }

        $script = <<<SCRIPT
            $(function() {
                $(".fixed-label").each(function(i, domEle) {
                    $(domEle).hide();
                    var arr = $(domEle).val().split(',');
                    arr.forEach((item,index,array)=>{
                        if (item != '') {
                            $(domEle).parent(".form-group").append('<a class="btn btn-default btn-sm" style="margin-right: 5px;" href="javascript:void(0);">'+item+'</a>');
                        }
                    })
                });
            });
SCRIPT;
        Admin::script($script);
        $this->text('', '固定标签')->default($info["ability_tag_al"])->setElementClass("fixed-label")->help("标签基于设计师发布的内容及相关设置通过算法标记，仅少部分标签可通过人工标记");
        $this->checkbox('ability_tag_op', '可选标签')->options(self::OPTIONAL_TAG)->checked($ability_tag_checked);
    }

}
